package io.renren.modules.generator.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.constant.UrlConstant;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.generator.dao.EnclosureDao;
import io.renren.modules.generator.entity.EnclosureEntity;
import io.renren.modules.generator.service.EnclosureService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;


@Service("enclosureService")
public class EnclosureServiceImpl extends ServiceImpl<EnclosureDao, EnclosureEntity> implements EnclosureService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<EnclosureEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(params.get("key").toString()))
            wrapper.like("enclosure_name", params.get("key"));
        IPage<EnclosureEntity> page = this.page(
                new Query<EnclosureEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void deleteEnclosureById(Integer enclosureId) {
        QueryWrapper<EnclosureEntity> wrapper = new QueryWrapper<>();
        wrapper.select("enclosure_id", "real_name");
        wrapper.eq("enclosure_id", enclosureId);
        EnclosureEntity enclosureEntity = baseMapper.selectOne(wrapper);
        String realName = enclosureEntity.getRealName();
        //文件真实存储位置
        String filePath = UrlConstant.dirUrl + realName;
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        } else {
            throw new RRException("文件不存在,请管理员手动检查文件存储地址");
        }
        baseMapper.deleteById(enclosureId);

    }

    @Override
    public IPage<Map<String, Object>> studentEnclosureList(Page<Map<String, Object>> page, Map<String, Object> params) {
        return baseMapper.studentEnclosureList(page, params);
    }

    @Override
    public IPage<Map<String, Object>> masterEnclosureList(Page<Map<String, Object>> page, Map<String, Object> params) {
        return baseMapper.masterEnclosureList(page, params);
    }

    @Override
    public IPage<Map<String, Object>> secretaryEnclosureList(Page<Map<String, Object>> page, Map<String, Object> params) {
        return baseMapper.secretaryEnclosureList(page, params);
    }

}
